import org.codehaus.groovy.grails.plugins.springsecurity.RedirectUtils
import org.grails.plugins.springsecurity.service.AuthenticateService

import org.springframework.security.AuthenticationTrustResolverImpl
import org.springframework.security.DisabledException
import org.springframework.security.context.SecurityContextHolder as SCH
import org.springframework.security.ui.AbstractProcessingFilter
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter

/**
 * Login Controller (Example).
 */
class LoginController {

    /**
     * Dependency injection for the authentication service.
     */
    def authenticateService

    /**
     * Dependency injection for OpenIDConsumer.
     */
    def openIDConsumer

    /**
     * Dependency injection for OpenIDAuthenticationProcessingFilter.
     */
    def openIDAuthenticationProcessingFilter

    private final authenticationTrustResolver = new AuthenticationTrustResolverImpl()

    def index = {
        if (isLoggedIn()) {
            redirect uri: '/'
        }
        else {
            redirect action: auth, params: params
        }
    }

    /**
     * Show the login page.
     */
    def auth = {

        nocache response

        if (isLoggedIn()) {
            redirect uri: '/inscricao/list'
            return
        }else{
            render "erro em auth"
        }

        String view
        String postUrl

        def config = authenticateService.securityConfig.security
        view = 'auth'
        postUrl = "${request.contextPath}${config.filterProcessesUrl}"

        render view: view, model: [postUrl: postUrl]
    }

    /**
     * Show denied page.
     */
    def denied = {
        if (isLoggedIn() && authenticationTrustResolver.isRememberMe(SCH.context?.authentication)) {
            // have cookie but the page is guarded with IS_AUTHENTICATED_FULLY
            redirect action: full, params: params
        }
    }

    /**
     * Login page for users with a remember-me cookie but accessing a IS_AUTHENTICATED_FULLY page.
     */
    def full = {
        render view: 'auth', params: params,
        model: [hasCookie: authenticationTrustResolver.isRememberMe(SCH.context?.authentication)]
    }


    /**
     * login failed
     */
    def authfail = {

        def username = session[AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY]
        def msg = ''
        def exception = session[AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY]
        if (exception) {
            if (exception instanceof DisabledException) {
                msg = "[$username] is disabled."
            }
            else {
                msg = "[$username] wrong username/password."
            }
        }

        if (isAjax()) {
            render "{error: '${msg}'}"
        }
        else {
            flash.message = msg
            redirect action: auth, params: params
        }
    }




    def recuperarSenha = {
        CriptografiaDescriptografia cripts  = new CriptografiaDescriptografia()
        def usuario = Usuario.findAllByEmail(params.email,['order':'desc'])[0]
if(usuario) {
            def myhtml = """
<center><img src="http://blog.sms.fortaleza.ce.gov.br/wp-content/themes/sms/images/brazao-pmf-220x100.gif" /></center>
            <h2>Bem vindo.</h2>
<p>Você Soliccou a Recuperação dos dados de Acesso </p>
<p>Esses são os seus dados de acesso.</p>
<p>Nome de usuário: ${usuario.username}</p>
<p>Senha: ${cripts.decriptografarSenha(usuario.keyPass)}</p>
<p><a href="${Configuracoes.link()}" >Página de acesso às informações</a></p>
<p>Ao acessar essa página, será necessário digitar o seu nome de usuário e a sena senha, portanto, aconselhamos que guarde esse e-mail.</p>
 
        """
           sendMail {
             to usuario.email
                from "selecao@sms.fortaleza.ce.gov.br"
                subject "Registro on-line ,Recuperação de Senha"
                html  myhtml
            }
         render "EMAIL ENVIADO COM SUCESSO"
} else 

        { render "NÃO FOI POSSIVEL ENCONTRAR ESTE EMAIL"
        }

      render ''
    }

    /**
     * Check if logged in.
     */
    private boolean isLoggedIn() {
        return authenticateService.isLoggedIn()
    }

    private boolean isAjax() {
        return authenticateService.isAjax(request)
    }

    /** cache controls */
    private void nocache(response) {
        response.setHeader('Cache-Control', 'no-cache') // HTTP 1.1
        response.addDateHeader('Expires', 0)
        response.setDateHeader('max-age', 0)
        response.setIntHeader ('Expires', -1) //prevents caching at the proxy server
        response.addHeader('cache-Control', 'private') //IE5.x only
    }
}
